<%-- 
    Document   : adminTools
    Created on : Aug 5, 2009, 11:31:28 AM
    Author     : david
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"
        import="com.google.appengine.api.users.UserService,
        com.google.appengine.api.users.UserServiceFactory, java.util.logging.Logger,
        com.appspot.nnaplanner.DAL.*, java.util.HashMap, java.util.ArrayList, java.util.List, com.appspot.nnaplanner.*" %>

<%
//MAP KEY
//ABQIAAAAM8o2I5tj16bQKMUb2eWgghTzyIyaiIcyVAbEGxsZymrytUhO-RS_jxXPLwrxa4PlQ_8lIjxxYUWbKw
            String Msg = "";
            if (request.getUserPrincipal() != null) {
                if (UserServiceFactory.getUserService().isUserAdmin()) {
                    Logger log = Logger.getLogger(this.getServletInfo());

                    if (request.getMethod().equals("POST")) {
                        if (request.getParameter("action").equals("stops")) {
                            int ID, NAME, DESC, LAT, LON;
                            ID = 0;
                            NAME = 1;
                            DESC = 2;
                            LAT = 3;
                            LON = 4;
                            String[] rows = request.getParameter("data").split("\n");
                            // add Stops
                            ArrayList<DALConnection> walks = new ArrayList<DALConnection>();
                            for (int i = 0; i < rows.length; i++) {
                                String[] stops = rows[i].split(",");
                                DALStop ds = new DALStop(stops[ID].trim(), stops[NAME].trim(), stops[DESC].trim());
                                ds.setKeywords(Utils.getKeywords(ds.getName()));
                                ds.getKeywords().add(ds.getID());
                               // out.print("<p>" + ds.getKeywords());
                                ds.setLatitude(Float.parseFloat(stops[LAT]));
                                ds.setLongitude(Float.parseFloat(stops[LON]));
                                Utils.generateConnections(ds);
                            }

                            log.info(" Inserted vertex " + NNappData.getGraph().vertexSet().size());
                            log.info(" Inserted Edges " + NNappData.getGraph().edgeSet().size());
                            DALGraph dg = new DALGraph();
                            dg.save(NNappData.getGraph());
                            Msg = "<p>Inserted " + rows.length + " Stops!</p>";

                        } else if (request.getParameter("action").equals("conns")) {
                            int SID = 0, SNAME = 1, DID = 2, DNAME = 3;
                            String[] rows = request.getParameter("data").split("\n");
                            ArrayList<String> updateStops = new ArrayList<String>();

                            HashMap<String, Integer> connCount = new HashMap<String, Integer>();
                            int counter = 0;
                            for (int i = 0; i < rows.length; i++) {
                                String[] conns = rows[i].split(",");
                                DALConnection dc = new DALConnection();
                                dc.setStop(conns[SID].trim());
                                dc.setStopName(conns[SNAME].trim());
                                dc.setDestination(conns[DID].trim());
                                dc.setDestinationName(conns[DNAME].trim());
                                dc.setID(conns[SID].trim() + conns[DID].trim());
                                dc.setKeywords(Utils.getKeywords(dc.getStopName()));
                                dc.getKeywords().add(dc.getID());
                                dc.getKeywords().add(dc.getStopID());
                                dc.getKeywords().add(dc.getDestinationID());
                                dc.save();
                                if (!updateStops.contains(dc.getStopID())) {
                                    updateStops.add(dc.getStopID());
                                    connCount.put(dc.getStopID(), 1);
                                }
                                if (!updateStops.contains(dc.getDestinationID())) {
                                    updateStops.add(dc.getDestinationID());
                                    connCount.put(dc.getDestinationID(), 1);
                                }
                                counter = connCount.get(dc.getStopID());
                                connCount.put(dc.getStopID(), counter + 1);
                                counter = connCount.get(dc.getDestinationID());
                                connCount.put(dc.getDestinationID(), counter + 1);
                            }

                            DALStop ds = new DALStop();
                            int count = 0;
                            for (String stopid : updateStops) {
                                ds = ds.getByID(stopid);
                                ds.setConnected(true);
                                ds.save();
                                count++;

                            }
                            log.info("Updated " + count + " stops");
                            Msg = "<p>Inserted " + rows.length + " Connections!</p>";

                        } else if (request.getParameter("action").equals("times")) {
                            int ID = 0, TIME = 1, DUR = 2, DESC = 3;
                            String[] rows = request.getParameter("data").split("\n");
                            DALConnection dc = new DALConnection();
                            java.util.ArrayList<DALConnection> conns = new java.util.ArrayList<DALConnection>();
                            for (int i = 0; i < rows.length; i++) {
                                String[] deps = rows[i].split(",");
                                dc = new DALConnection();
                                dc.setID(deps[ID].trim());
                                java.text.DateFormat df = new java.text.SimpleDateFormat("HH:mm");
                                java.util.Date d = df.parse(deps[TIME].trim());
                                Integer duration = Integer.parseInt(deps[DUR].trim());
                                if (conns.contains(dc)) {
                                    //out.print("<br> found: " + deps[ID] );
                                    conns.get(conns.indexOf(dc)).addDeparture(d, duration, deps[DESC].trim());
                                } else {
                                    //out.print("<br> added: " + deps[ID] );
                                    dc = dc.getByID(deps[ID]);
                                    dc.addDeparture(d, duration, deps[DESC].trim());
                                    conns.add(dc);
                                }
                            }
                            for (DALConnection d : conns) {
                                //out.print("<p> " + d.getTimes().size());
                                float duration = d.getDurations().get(0);
                                d.setDepartures(d.getTimes().size());
                                d.save();
                                NNappData.getGraph().addEdge(d.getStopID(), d.getDestinationID());
                                NNappData.getGraph().setEdgeWeight(NNappData.getGraph().getEdge(d.getStopID(), d.getDestinationID()), duration);
                            }
                            DALGraph dg = new DALGraph();
                            dg.save(NNappData.getGraph());
                            Msg = "<p>Inserted " + conns.size() + " Connections Times!</p>";
                        }

                    }
                }
            }
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>nnap - Admin Tools</title>
        <link rel="stylesheet" type="text/css" href="/ext/resources/css/ext-all.css"/>
        <style type="text/css" media="screen">@import url(/styles/main.css);</style>
        <script type="text/javascript" src="/ext/adapter/ext/ext-base.js"></script>
        <script type="text/javascript" src="/ext/ext-all.js"></script>


    </head>
    <body>
        <div class="header">
            <%@include file="Header.jspf" %>
            <%@include file="Authenticator.jspf" %>
            <% if (request.getUserPrincipal() == null) {
                return;
            }

            if (!UserServiceFactory.getUserService().isUserAdmin()) {
                return;
            }%>
        </div>

        <br>

        <script>
            Ext.onReady(function(){

                var tabs = new Ext.TabPanel({
                    renderTo: 'tools',
                    width:650,
                    height:500,
                    activeTab: 0,
                    plain:true,
                    defaults:{autoHeight: true},
                    items:[
                        {contentEl:'stops', title: 'CSV Stops'},
                        {contentEl:'conns', title: 'CSV Connections'},
                        {contentEl:'times', title: 'CSV Times'},
                        {contentEl:'info', title: 'Infomration'}
                    ]
                });
                var grid = new Ext.TableGrid("info-table", {
                    stripeRows: true // stripe alternate rows
                });
                grid.render();
                

            });            
        </script>

        <div id="tools">
            <div> <script language="javascript">
                var msg = '<%=Msg%>';
                if (msg.length >1) Ext.MessageBox.alert('Information',msg);
                </script></div>
            <div id="stops" class="x-hide-display">

                <div style="padding:10px">
                    <h2>STOPS</h2>
                    <p>Use this form to mass insert comma seperated stops. Paste comma seperated values below</p>
                    <i>Format: stop id, stop name, description, latitude, longitude</i>
                    <form action="/adminTools.jsp?action=stops" method="post" >
                        <textarea name="data" style="width:100%" rows="20" cols="5"></textarea>
                        <input type="submit" value="Insert">
                    </form>
                </div>
            </div>
            <div id="conns" class="x-hide-display">
                <div style="padding:10px">
                    <h2>CONNECTIONS</h2>
                    <p>Use this form to mass insert comma seperated stops. Paste comma seperated values below</p>
                    <i>Format: stop id, stop name, destination id, destination name </i>
                    <form action="/adminTools.jsp?action=conns" method="post" >
                        <textarea name="data" style="width:100%" rows="20" cols="5"></textarea>
                        <input type="submit" value="Insert">
                    </form>
                </div>
            </div>
            <div id="times" class="x-hide-display">
                <div style="padding:10px">
                    <h2>CONNECTION TIMES</h2>
                    <p>Use this form to mass insert comma seperated stops. Paste comma seperated values below</p>
                    <i>Format: connection id, time (HH:MM), duration, description </i>
                    <form action="/adminTools.jsp?action=times" method="post" >
                        <textarea name="data" style="width:100%" rows="20" cols="5"></textarea>
                        <input type="submit" value="Insert">
                    </form>
                </div>
            </div>
            <div id="info" class="x-hide-display">
                <div style="padding:10px">
                    <h2>Infomration</h2>
                    <p>General details about this application</p>
                    <p>Graph Data:
                        <br /> - <b>Graph Vertices:</b> <%=NNappData.getGraph().vertexSet().size()%>
                        <br /> - <b>Graph Edges:</b> <%=NNappData.getGraph().edgeSet().size()%>
                    </p>
                </div>
            </div>
        </div>
    </body>
</html>
